/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class DefaultRenderFunc {
    static renderFuncs = {
        "sensor_msgs/Image": `\
    render.imageRgb(msg.data,msg.width,msg.height,1);`,
        "sensor_msgs/CompressedImage": `\
    render.imageJpg(msg.data, 1);`,
        "sensor_msgs/LaserScan": `\
    render.text(msg.range_min+"<range<"+msg.range_max, 0xff00ff00);
    let angle=msg.angle_min;
    let points=[]
    for(let i=0;i<msg.ranges.length;i++){
        if(msg.ranges[i]){
            if(msg.range_min<msg.ranges[i] && msg.ranges[i]<msg.range_max)
            {
                points.push([
                    Math.cos(angle)*msg.ranges[i]*50,
                    Math.sin(angle)*msg.ranges[i]*50
                ]);
            }
        angle+=msg.angle_increment;
    }
    render.text(points.length+"个有效点")
    points.push([0,0,0xff00ff00,5]);
    render.points2d(points);`,
        "sensor_msgs/PointCloud2": `\
    let scale = 50; // 点云渲染放大倍数,点云源数据以米为单位,渲染以像素为单位,放大50倍相当于:1米=50像素
    let isOrtho = true; // 正交/透视投影渲染
    let littleEndian = !msg.is_bigendian;
    let offsets = {};
    for (let field of msg.fields) {
        offsets[field.name] = field.offset;
    }
    let u8Array = new Uint8Array(msg.data);
    let u8View = new DataView(u8Array.buffer);
    let points = []; // 从源数据中提取点坐标，用于渲染
    for (let i = 0; i < msg.height * msg.width; i++) {
        let p = i * msg.point_step;
        let x = u8View.getFloat32(p + offsets['x'], littleEndian);
        let y = u8View.getFloat32(p + offsets['y'], littleEndian);
        let z = u8View.getFloat32(p + offsets['z'], littleEndian);
        if (x != y && y != z) { // 有效点
            points.push(x, -z, -y);
        }
    }
    render.text("宽 * 高 : " + msg.width + "x" + msg.height);
    render.text("有效点数 : " + points.length / 3);
    render.points3d(points, scale, isOrtho);`,
    }
    static getRenderFunc(msgType) {
        if (msgType in DefaultRenderFunc.renderFuncs) {
            return DefaultRenderFunc.renderFuncs[msgType];
        }
        return "";
    }
}

module.exports = DefaultRenderFunc;